<template>
  <div class="rf-upload-picture">
    <el-upload
      ref="uploadImage"
      :action="url"
      list-type="picture-card"
      :on-success="handleMoreSuccess"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-error="handleError"
      :limit="maxLength"
      :class="{disabled:uploadDisabled}"
      :file-list="files"
      :data="params"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <div
      v-if="previewVisible"
      class="preview-bg"
      @click="previewVisible=false"
    >
      <div class="preview-image">
        <img :src="dialogImageUrl">
      </div>
    </div>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import { uploadFileUrl } from '@/api/upload'
export default {
  name: 'RfUploadPict',
  props: {
    maxLength: {
      type: Number,
      default: 1
    },
    imageUrl: {
      type: String
    },
    // 图片上传的宽高限制
    limitOption: {
      type: Object,
      default: () => {
        return {
          width: '',
          height: ''
        }
      }
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      previewVisible: false,
      url: uploadFileUrl(),
      currentPicLegnth: 0,
      params: {},
      files: []
    }
  },
  computed: {
    uploadDisabled: function() {
      return this.maxLength < 2 && this.currentPicLegnth > 0
    }
  },
  watch: {
    imageUrl: {
      immediate: true,
      handler(value) {
        if (!!value && value != '') {
          this.files = value.split(',').map(item => {
            return {
              'url': item
            }
          })
        } else {
          this.files = []
        }
        this.currentPicLegnth = this.files.length
      }
    }
  },
  mounted() {
    this.params.access_token = Cookies.get('lms_token')
  },
  methods: {
    // 校验图片的尺寸
    beforeUpload(file) {
      if (!this.limitOption.width || !this.limitOption.height) return true
      const isSize = new Promise((resolve, reject) => {
        const width = this.limitOption.width
        const height = this.limitOption.height
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          const valid = img.width === width && img.height === height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(() => {
        return file
      }, () => {
        this.$message.error(`${this.$t('TIP.PIC_SIZE_LIMIT')}${this.limitOption.width}px x ${this.limitOption.height}px`)
        return Promise.reject()
      })
      return isSize
    },
    // 移除图片操作
    handleRemove(file, fileList) {
      const url = fileList.map(item => {
        if (item.percentage === 100) {
          return item.response.data.url
        } else {
          return item.url
        }
      }).toString()
      this.currentPicLegnth = url.length
      this.getImage(url)
    },
    // 图片预览操作
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.previewVisible = true
    },
    // 图片上传成功操作
    handleMoreSuccess(response, file, fileList) {
      console.log(fileList)
      const url = fileList.map(item => {
        if (item.percentage === 100) {
          return item.response.data.url
        } else {
          return item.url
        }
      }).toString()
      this.currentPicLegnth = url.length
      this.getImage(url)
    },
    // 图片上传失败提示
    handleError(err, flie, flieList) {
      this.$message.error(this.$t('TIP.UPLOAD_ERROR'))
    },
    // 图片变动传递事件
    getImage(data) {
      this.$emit('getImage', data)
    },
    // 清除
    clear() {
      this.$refs['uploadImage'].clearFiles()
    }
  }
}
</script>
<style lang="scss" scoped>
  .preview-bg {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;

    .preview-image {
      img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        max-width: 100%;
        max-height: 100%;
      }
    }
  }

  .image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .image-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
  }

  .image {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 6px;
  }
</style>
